﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;

namespace Pahan.McuFusion.Common.Xml
{
    public static class XmlNodeExtensions
    {
        public static IEnumerable<XmlElement> Elements(this XmlNode node)
        {
            return node.ChildNodes.OfType<XmlElement>();
        }

        public static IEnumerable<XmlElement> Elements(this XmlNode node, String localName)
        {
            return node.ChildNodes.OfType<XmlElement>().Where(n => n.LocalName == localName);
        }

        public static XmlElement Element(this XmlNode node)
        {
            return node.ChildNodes.OfType<XmlElement>().FirstOrDefault();
        }

        public static XmlElement Element(this XmlNode node, String localName)
        {
            return node.ChildNodes.OfType<XmlElement>().FirstOrDefault(n => n.LocalName == localName);
        }

        public static int ValueAsInt32(this XmlNode node)
        {
            return Convert.ToInt32(node.Value);
        }

        public static byte ValueAsHexByte(this XmlNode node)
        {
            return byte.Parse(node.Value, System.Globalization.NumberStyles.HexNumber);
        }

        public static bool ValueAsBool(this XmlNode node)
        {
            switch (node.Value.ToLowerInvariant())
            {
                case "0":
                case "false":
                    return false;
                case "1":
                case "true":
                    return true;
                default:
                    return false;
            }
        }

        public static T? AttributeValue<T>(this XmlNode node, String name)
            where T : struct
        {
            var attr = node.Attributes[name];
            if (attr == null)
            {
                return null;
            }
            else
            {
                return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(attr.Value);
            }
        }

        public static T AttributeValue<T>(this XmlNode node, String name, T @default) 
            where T : struct
        {
            return node.AttributeValue<T>(name) ?? @default;
        }
    }
}